package com.parcool.mycroppicandupload;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Calendar;

import com.parcool.mycroppicandupload.utils.AppConstant;
import com.parcool.mycroppicandupload.utils.Utils;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

	private Button btnSelect;
	private ImageView ivResult;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		init();
	}

	// 初始化控件
	private void init() {
		// TODO Auto-generated method stub
		btnSelect = (Button) findViewById(R.id.btn_select);
		btnSelect.setOnClickListener(this);
		ivResult = (ImageView) findViewById(R.id.iv_result);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_select:
			Utils.getInstance().selectPicture(this);
			break;

		case R.id.iv_result:
			break;
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode != Activity.RESULT_OK) {
			return;
		}
		if (null == data) {
			return;
		}
		Uri uri = null;
		if (requestCode == AppConstant.KITKAT_LESS) {
			uri = data.getData();
			Log.d("tag", "uri=" + uri);
			// 调用裁剪方法
			Utils.getInstance().cropPicture(this, uri);
		} else if (requestCode == AppConstant.KITKAT_ABOVE) {
			uri = data.getData();
			Log.d("tag", "uri=" + uri);
			// 先将这个uri转换为path，然后再转换为uri
			String thePath = Utils.getInstance().getPath(this, uri);
			Utils.getInstance().cropPicture(this,
					Uri.fromFile(new File(thePath)));
		} else if (requestCode == AppConstant.INTENT_CROP) {
			Bitmap bitmap = data.getParcelableExtra("data");
			ivResult.setImageBitmap(bitmap);
			File temp = new File(Environment.getExternalStorageDirectory()
					.getPath() + "/yourAppCacheFolder/");// 自已缓存文件夹
			if (!temp.exists()) {
				temp.mkdir();
			}
			File tempFile = new File(temp.getAbsolutePath()+"/"
					+ Calendar.getInstance().getTimeInMillis() + ".jpg"); // 以时间秒为文件名
			// 图像保存到文件中
			FileOutputStream foutput = null;
			try {
				foutput = new FileOutputStream(tempFile);
				if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, foutput)) {
					Toast.makeText(MainActivity.this,
							"已生成缓存文件，等待上传！文件位置：" + tempFile.getAbsolutePath(),
							Toast.LENGTH_LONG).show();
				}
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
